package pers.qianyu.month_202011.date_20201114;

/**
 * 704. 二分查找
 * https://leetcode-cn.com/problems/binary-search/
 *
 * @author mizzle rain
 * @date 2020-11-14 17:04
 */
public class BinSearch {
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            // 防止整数溢出
            int mid = left + ((right - left) >> 1);
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {0, 1, 2, 3, 4, 5, 6};
        int result = new BinSearch().search(arr, 2);
        System.out.println("result = " + result);
    }
}
